import { Init, Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsInfoEntity } from '../entity/info';
import { GoodsSpecService } from './spec';
import { ProcedureBaseService } from '../../../comm/service/procedure.base.service';
import { In, Like } from 'typeorm';
import { GoodsTypeEntity } from '../entity/type';

/**
 * 商品信息
 */
@Provide()
export class GoodsInfoService extends BaseService {
  @InjectEntityModel(GoodsInfoEntity)
  goodsInfoEntity: Repository<GoodsInfoEntity>;

  @Inject()
  goodsSpecService: GoodsSpecService;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.goodsInfoEntity);
    this.entity = this.goodsInfoEntity;
    // this.procedurePrefix = 'sp_goods_info_';
    // this.enableProcedure = false;
  }

  /**
   * 修改之后
   * @param data
   * @param type
   */
  async modifyAfter(data: any, type: 'add' | 'update' | 'delete') {
    if ((type == 'add' || type == 'update') && data.specs) {
      // 保存规格
      await this.goodsSpecService.save(data.id, data.specs);
    }
    if (type == 'delete') {
      // 删除规格
      await this.goodsSpecService.removeByGoodsId([data.id]);
    }
  }

  /**
   * 详情
   * @param id
   * @param infoIgnoreProperty
   * @returns
   */
  async info(id: any, infoIgnoreProperty?: string[]) {
    if (!id) return;
    const info = await super.info(id, infoIgnoreProperty);
    if (info) {
      // 获取规格
      info.specs = await this.goodsSpecService.getByGoodsId(info.id);
    }
    return info;
  }

  async getGoodsFromFixture(params: any) {
    const {
      source = 'source-3',
      num = 99,
      typeIds = [],
      ids = [],
      attribute = 0,
    } = params;
    let list = [];
    switch (source) {
      case 'source-1':
        // 根据商品ID列表获取商品，状态为1，按排序号降序，限制获取数量
        list = await this.goodsInfoEntity.find({
          where: { id: In(ids), status: 1 },
          order: { sortNum: 'DESC' },
          take: num,
        });
        break;
      case 'source-2':
        if (typeIds.length) {
          // 根据商品类型ID获取商品，状态为1，按排序号降序，限制获取数量
          list = await this.goodsInfoEntity.find({
            where: { typeId: In(typeIds), status: 1 },
            order: { sortNum: 'DESC' },
            take: num,
          });
        }
        break;
      case 'source-3':
        // 根据属性和状态获取商品，按排序号降序，限制获取数量
        if (attribute) {
          const attributes = attribute.toString().split(',');
          const whereConditions = attributes.map(attr => ({
            attribute: Like(`%${attr}%`),
            status: 1
          }));
          list = await this.goodsInfoEntity.find({
            where: whereConditions,
            order: { sortNum: 'DESC' },
            take: num,
          });
        } else {
          list = await this.goodsInfoEntity.find({
            where: { status: 1 },
            order: { sortNum: 'DESC' },
            take: num,
          });
        }
        break;
      default:
        break;
    }
    return list;
  }

  /**
   * 分页查询（支持近效期查询）
   */
  async pageWithValDate(params) {
    const { isNextValPrice, ...restParams } = params;
    const query = this.goodsInfoEntity
      .createQueryBuilder('a')
      .leftJoinAndSelect(GoodsTypeEntity, 'b', 'a.typeId = b.id')
      .select([
        'a.*', 
        'b.name as typeName'
      ])
      .where('a.status = :status', { status: 1 });

    // 处理价格区间
    if (params.minPrice) {
      query.andWhere('a.price >= :minPrice', { minPrice: params.minPrice });
    }
    if (params.maxPrice) {
      query.andWhere('a.price <= :maxPrice', { maxPrice: params.maxPrice });
    }

    // 处理属性查询
    if (params.attribute && params.attribute.length > 0) {
      const attributes = params.attribute.toString().split(',');
      const attrConditions = attributes.map((attr, index) => {
        return `a.attribute LIKE :attr${index}`;
      });
      query.andWhere(`(${attrConditions.join(' OR ')})`, 
        attributes.reduce((acc, attr, index) => {
          acc[`attr${index}`] = `%${attr}%`;
          return acc;
        }, {})
      );
    }

    // 处理商品类型多选查询
    if (params.typeIds && params.typeIds.length > 0) {
      const typeIdList = params.typeIds
        .toString()
        .split(',')
        .map(Number)
        .filter(id => !isNaN(id));
      if (typeIdList.length > 0) {
        query.andWhere('a.typeId IN (:typeIdList)', { typeIdList });
      }
    }

    // 只查询近效期商品（180天内到期，使用nearestExpiredDate字段）
    const futureDate = new Date();
    futureDate.setDate(futureDate.getDate() + 180);
    query.andWhere('a.nearestExpiredDate <= :futureDate', { futureDate })
      .andWhere('a.nearestExpiredDate IS NOT NULL');

    // 处理关键字搜索
    if (params.keyWord) {
      const keyWordFields = [
        'title',
        'goodsCode',
        'oracleGoodsName',
        'manufacturer',
        'goodsCode',
        'logogram'
      ];
      const keyWordConditions = keyWordFields.map(field => `a.${field} LIKE :keyWord`);
      query.andWhere(`(${keyWordConditions.join(' OR ')})`, { keyWord: `%${params.keyWord}%` });
    }

    // 分页处理
    const page = Number(params.page) || 1;
    const size = Number(params.size) || 10;
    query.skip((page - 1) * size).take(size);

    // 排序处理
    if (params.order && params.sort) {
      const {sort, order} = params;
      query.orderBy(`a.${order}`, sort.toUpperCase())
        .addOrderBy('a.nearestExpiredDate', 'ASC');
    } else {
      query.orderBy('a.createTime', 'DESC')
        .addOrderBy('a.nearestExpiredDate', 'ASC');
    }

    // 执行查询
    const [list, total] = await Promise.all([
      query.getRawMany(),
      query.getCount(),
    ]);

    // 处理返回数据
    const processedList = list.map(item => {
      // 如果是近效期查询，将 nextValPrice 覆盖到 price
      if (isNextValPrice) {
        item.price = item.nextValPrice || 0;
      }

      return item;
    });

    return {
      list: processedList,
      pagination: {
        page,
        size,
        total,
      },
    };
  }
}
